package dshop.service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import appbase.utils.DateUtil;
import dshop.model.procurement.Procurement;
import io.rong.RongCloud;
import io.rong.messages.BaseMessage;
import io.rong.methods.message._private.Private;
import io.rong.models.message.PrivateMessage;
import io.rong.models.response.ResponseResult;
import io.rong.util.GsonUtil;

public class RongCloudService {

    private static String APP_KEY = "app_key";
    private static String APP_SECRET = "app_secret";
	
    private static Integer APP_SENDER_ID;
    
    private static String DESC_ON_PUSH_PROCUREMENT = "及时通向您推送一条采购信息";
    private static String DESC_ON_END_PROCUREMENT = "及时通通知您采购信息已结束";
    
    private static int TYPE_ON_PUSH_PROCUREMENT = 1;
    private static int TYPE_ON_END_PROCUREMENT = 2;
    
    public static void initRongCloud(String appKey, String appSecret, Integer appSenderId)
    {
    		APP_KEY = appKey;
    		APP_SECRET = appSecret;
    		APP_SENDER_ID = appSenderId;
    }
	
    
    public static void onPushProcurement(List<Integer> userIdList, ProcurementDto procurement)
    {
    		if (userIdList == null || userIdList.isEmpty())
    		{
    			return;
    		}
    		
    		if (userIdList.size() < 1000)
    		{
    			sendProcurementMessageSmallList(userIdList, procurement, DESC_ON_PUSH_PROCUREMENT, TYPE_ON_PUSH_PROCUREMENT);
    			return;
    		}
    		
    		List<List<Integer>> listOfChildList = subToChildList(userIdList, 1000);
    		for (List<Integer> childList : listOfChildList) 
    		{
    			sendProcurementMessageSmallList(childList, procurement, DESC_ON_PUSH_PROCUREMENT, TYPE_ON_PUSH_PROCUREMENT);
		}
    }
    
    
    public static void onEndProcurement(List<Integer> userIdList, ProcurementDto procurement)
    {
    		if (userIdList == null || userIdList.isEmpty())
    		{
    			return;
    		}
    		
    		if (userIdList.size() < 1000)
    		{
    			sendProcurementMessageSmallList(userIdList, procurement, DESC_ON_END_PROCUREMENT, TYPE_ON_END_PROCUREMENT);
    			return;
    		}
    		
    		List<List<Integer>> listOfChildList = subToChildList(userIdList, 1000);
    		for (List<Integer> childList : listOfChildList) 
    		{
    			sendProcurementMessageSmallList(childList, procurement, DESC_ON_END_PROCUREMENT, TYPE_ON_END_PROCUREMENT);
		}
    }
    

	private static List<List<Integer>> subToChildList(List<Integer> userIdList, int childListSize) 
	{
		List<List<Integer>> listOfChildList = new ArrayList<>();
		int fromIndex = 0;
		int toIndex = 0;
		while (toIndex < userIdList.size()) 
		{
			toIndex = fromIndex + childListSize;
			if (toIndex > userIdList.size())
			{
				toIndex = userIdList.size();
			}
			List<Integer> childUserIdList = userIdList.subList(fromIndex, toIndex);
			listOfChildList.add(childUserIdList);
			fromIndex = toIndex;
		}
		return listOfChildList;
	}
    
	private static void sendProcurementMessageSmallList(List<Integer> userIdList, ProcurementDto procurement, String desc, int type)
	{
		RongCloud rongCloud = RongCloud.getInstance(APP_KEY, APP_SECRET);
		Private privates = rongCloud.message.msgPrivate;
		
		AppPuchaseMessageContent content = new AppPuchaseMessageContent(procurement, desc, type);
		
		String senderId = formatToRongCloudUserId(APP_SENDER_ID);
		String[] targetIds = formatToRongCloudUserId(userIdList);
		
		PrivateMessage privateMessage = new PrivateMessage()
                .setSenderId(senderId)
                .setTargetId(targetIds)
                .setObjectName(content.getType())
                .setContent(content)
                .setPushContent("")
                .setPushData("")
                .setCount("1")
                .setVerifyBlacklist(0)
                .setIsPersisted(0)
                .setIsCounted(0)
                .setIsIncludeSender(0);
		try {
			ResponseResult privateResult = privates.send(privateMessage);
			System.out.println("send private message:  " + privateResult.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	private static String[] formatToRongCloudUserId(List<Integer> userIdList) 
	{
		if (userIdList == null || userIdList.isEmpty())
		{
			return new String[0];
		}
		
		String[] userIds = new String[userIdList.size()];
		for (int i = 0; i < userIdList.size(); i++) 
		{
			userIds[i] = formatToRongCloudUserId(userIdList.get(i));
		}
		return userIds;
	}


	private static String formatToRongCloudUserId(Integer userId) 
	{	
		String userIdStr = new DecimalFormat(",###").format(userId);
		return userIdStr;
	}


	public static void main(String[] args) {
		String appKey = "8brlm7uf8i4o3";
		String appSecret = "RCOKzduBbXrnDe";
		Integer senderId = 8216;
		
		initRongCloud(appKey, appSecret, senderId);
		
		List<Integer> userIdList = new ArrayList<>();
		userIdList.add(8227);
		
		Integer procurementId = 7759;
		String productName = "求购小米Max";
		String productDecription = "小米Max超级版";
		String buyNumber = "100台";
		String city = "深圳";
		List<String> displayImg = new ArrayList<>();
		Date startDateTime = new Date();
		Date endDateTime = new Date();
		ProcurementDto procurement = new ProcurementDto(procurementId, productName, productDecription, buyNumber, city, displayImg, startDateTime, endDateTime);
		onPushProcurement(userIdList, procurement);
	}
	
	/*public static void main(String[] args) {
		List<Integer> list = new ArrayList<>();
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(4);
		list.add(5);
		list.add(6);
		list.add(7);
		list.add(8);
		list.add(9);
		list.add(10);
		
		List<List<Integer>> listOfChildList = subToChildList(list, 3);
		System.out.println(listOfChildList);
		System.err.println(JsonKit.toJson(listOfChildList));
	}*/
	
	
	@SuppressWarnings("unused")
	static class AppPuchaseMessageContent extends BaseMessage{
		
		private Integer senderId;
		private Integer type;
		private String desc;
		private String purchase;
		
		AppPuchaseMessageContent(ProcurementDto purchase, String desc, int type)
		{
			this.senderId = 0;
			this.type = type;
			this.desc = desc;
			this.purchase = GsonUtil.toJson(purchase, ProcurementDto.class);
		}
		
		@Override
		public String getType() {
			return "app:puchaseMsg";
		}

		@Override
		public String toString() {
//			return GsonUtil.toJson(this, AppPuchaseMessageContent.class);
			return purchase;
		}
	}
	
	@SuppressWarnings("unused")
	public static class ProcurementDto{
		private Integer id = 0;
		private Double longitude = 0.0;
		private Double latitude = 0.0;
		private List<String> displayImg = new ArrayList<String>();
		
		private String contactName = "";
		private String contactPhone = "";
		private String contactEmail = "";
		
		private Integer countryCode = 0;
		private Integer provinceCode = 0;
		private Integer cityCode = 0;
		private Integer areaCode = 0;
		
		private String provinceName = "";
		private String cityName = "";
		private String areaName = "";
		private String address = "";
		private String city = "";
		
		private String startDateTime = "";
		private String endDateTime = "";
		
		private String companyName = "";
		
		private String productName = "";
		private String productSpecification = "";
		private String productDescription = "";
		private String productIndustryName = "";
		
		private String buyNumber = "";
		
		private String status = Procurement.STRUTS_NORMAL;
		
		public ProcurementDto(Integer id, String productName, String productDecription, String buyNumber, String city, List<String> displayImg, Date startDateTime, Date endDateTime){
			this.id = id;
			this.productName = productName;
			this.productDescription = productDecription;
			this.buyNumber = buyNumber;
			this.city = city;
			this.displayImg = displayImg;
			
			this.startDateTime = DateUtil.dateFormat("yyyy-MM-dd HH:mm:ss", startDateTime);
			this.endDateTime = DateUtil.dateFormat("yyyy-MM-dd HH:mm:ss", endDateTime);
			
			if (endDateTime != null && endDateTime.before(new Date()))
			{
				this.status = Procurement.STRUTS_END;
			}
		}
	}
	
}
